package com.chzc.fm.duotin.utils;

import android.os.AsyncTask;

import java.io.File;

/**
 * Created by BillSinla on 2016/6/7.
 */
public class DuotinTask extends AsyncTask<Void, Void, Object> {

    private IRequest request;

    private IRequestCallback callback;

    private IDownloadListener listener;

    private IDownloadRequest downloadRequest;

    public DuotinTask(IRequest request, IRequestCallback callback){
        if(request == null || callback == null){
            throw new NullPointerException("IRequest or IRequestCallback can not be null!!!");
        }
        this.request = request;
        this.callback = callback;
    }

    public DuotinTask(IDownloadRequest request, IDownloadListener listener){
        if(request == null || listener == null){
            throw new NullPointerException("IDownloadRequest or IDownloadListener can not be null!!!");
        }
        this.downloadRequest = request;
        this.listener = listener;
    }




    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Object doInBackground(Void... params) {
        if(request == null){
            return downloadRequest.doRequest(listener);
        }else {
            return request.doRequest();
        }
    }

    @Override
    protected void onPostExecute(Object result) {
        if(callback == null) {
            return;
        }
        if(result == null){
            callback.error("请求失败了...");
        }else{
            callback.success(result);
        }
    }


    /**
     * 请求接口(商品信息：你要买什么)
     * */
    public interface IRequest{
        /**
         * 执行网络请求
         * */
        Object doRequest();
    }

    /**
     * 请求结果回调（收货人信息：）
     * */
    public interface IRequestCallback{
        /**
         * 成功回调
         *
         * @param object 请求结果
         * */
        void success(Object object);

        /**
         * 错误回调
         *
         * @param msg 错误信息
         * */
        void error(String msg);
    }

    public interface IDownloadRequest{
        Object doRequest(IDownloadListener listener);
    }

    /**
     * 下载监听
     */
    public interface IDownloadListener{
        /**
         * 更新进度
         */
        void upgradeProgress(float progress);

        /**
         * 下载完成
         */
        void onComplete(File file);

        /**
         * 下载失败
         */
        void onFail(String msg);

        /**
         * 开始下载
         */
        void start();

    }
}
